#!/bin/sh /etc/rc.common
# Copyright (C) 2017 OpenWrt.org

START=95

USE_PROCD=1

CONF=/var/etc/mentohust.conf
CONF_TMP=${CONF}.tmp

start_service() {
	if [ "x$(uci get mentohust.@option[0].rproxy)" = x1 ]; then
		modprobe rproxy 2>/dev/null
		test -f /tmp/nf_conntrack_max_bak || {
			cat /proc/sys/net/nf_conntrack_max >/tmp/nf_conntrack_max_bak
		}
		nf_limit="$(uci get mentohust.@option[0].nf_limit)"
		[ "x$nf_limit" = "x0" ] || {
			echo $nf_limit >/proc/sys/net/nf_conntrack_max
		}
	else
		rmmod rproxy 2>/dev/null
		sysctl -w `cat /etc/sysctl.conf | grep net.netfilter.nf_conntrack_max`
		test -f /tmp/nf_conntrack_max_bak && {
			cat /tmp/nf_conntrack_max_bak >/proc/sys/net/nf_conntrack_max
			rm -f /tmp/nf_conntrack_max_bak
		}
	fi

	[ "x$(uci get mentohust.@option[0].enable)" = x1 ] || {
		test -e /etc/mentohust.conf && /usr/sbin/mentohust -k
		return 0
	}

	mkdir -p /var/etc

	echo [MentoHUST] >$CONF_TMP
	echo ServiceName=$(uci get mentohust.@mentohust[0].ServiceName) >> $CONF_TMP
	echo Username=$(uci get mentohust.@mentohust[0].Username) >> $CONF_TMP
	echo Password=$(uci get mentohust.@mentohust[0].Password) >> $CONF_TMP
	echo Nic=$(uci get mentohust.@mentohust[0].Nic) >> $CONF_TMP
	echo IP=$(uci get mentohust.@mentohust[0].IP) >> $CONF_TMP
	echo Mask=$(uci get mentohust.@mentohust[0].Mask) >> $CONF_TMP
	echo Gateway=$(uci get mentohust.@mentohust[0].Gateway) >> $CONF_TMP
	echo DNS=$(uci get mentohust.@mentohust[0].DNS) >> $CONF_TMP
	echo PingHost=$(uci get mentohust.@mentohust[0].PingHost) >> $CONF_TMP
	echo Timeout=$(uci get mentohust.@mentohust[0].Timeout) >> $CONF_TMP
	echo EchoInterval=$(uci get mentohust.@mentohust[0].EchoInterval) >> $CONF_TMP
	echo RestartWait=$(uci get mentohust.@mentohust[0].RestartWait) >> $CONF_TMP
	echo MaxFail=$(uci get mentohust.@mentohust[0].MaxFail) >> $CONF_TMP
	echo StartMode=$(uci get mentohust.@mentohust[0].StartMode) >> $CONF_TMP
	echo DhcpMode=$(uci get mentohust.@mentohust[0].DhcpMode) >> $CONF_TMP
	echo DaemonMode=$(uci get mentohust.@mentohust[0].DaemonMode) >> $CONF_TMP
	echo ShowNotify=$(uci get mentohust.@mentohust[0].ShowNotify) >> $CONF_TMP
	echo Version=$(uci get mentohust.@mentohust[0].Version) >> $CONF_TMP
	echo DataFile=$(uci get mentohust.@mentohust[0].DataFile) >> $CONF_TMP
	echo DhcpScript=$(uci get mentohust.@mentohust[0].DhcpScript) >> $CONF_TMP

	[ x`readlink /etc/mentohust.conf` = x$CONF ] || ln -sf $CONF /etc/mentohust.conf
	mv $CONF_TMP $CONF

	/usr/sbin/mentohust -k

	procd_open_instance
	procd_set_param command /usr/sbin/mentohust
	procd_set_param file $CONF
	procd_set_param respawn
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_close_instance
}
